import { init } from 'snabbdom/build/package/init'
import { h } from 'snabbdom/build/package/h'
// 1、导入模块
import { styleModule } from "snabbdom/build/package/modules/style"
import { eventListenersModule } from "snabbdom/build/package/modules/eventlisteners"

const patch = init([styleModule, eventListenersModule])
// 初始数据
var originalData = [
    { rank: 1, title: 'The Shawshank Redemption', desc: 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', elmHeight: 0 },
    { rank: 2, title: 'The Godfather', desc: 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', elmHeight: 0 },
    { rank: 3, title: 'The Godfather: Part II', desc: 'The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.', elmHeight: 0 },
    { rank: 4, title: 'The Dark Knight', desc: 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.', elmHeight: 0 },
    { rank: 5, title: 'Pulp Fiction', desc: 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', elmHeight: 0 },
    { rank: 6, title: 'Schindler\'s List', desc: 'In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.', elmHeight: 0 },
    { rank: 7, title: '12 Angry Men', desc: 'A dissenting juror in a murder trial slowly manages to convince the others that the case is not as obviously clear as it seemed in court.', elmHeight: 0 },
    { rank: 8, title: 'The Good, the Bad and the Ugly', desc: 'A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.', elmHeight: 0 },
    { rank: 9, title: 'The Lord of the Rings: The Return of the King', desc: 'Gandalf and Aragorn lead the World of Men against Sauron\'s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', elmHeight: 0 },
    { rank: 10, title: 'Fight Club', desc: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more...', elmHeight: 0 },
]
// 用来保持原有数据不变
var data = [
    originalData[0],
    originalData[1],
    originalData[2],
    originalData[3],
    originalData[4],
    originalData[5],
    originalData[6],
    originalData[7],
    originalData[8],
    originalData[9],
]
// 排序关键字
var sortItems = ['rank', 'title', 'desc']
// 定义旧的需要替换的列表vnode,第一次通过获取dom,第二次之后对比虚拟dom
var oldListView = undefined
// 添加movie
function add() {
    let n = Math.floor(Math.random() * 10)
    let movie = {
        rank: data.length + 1,
        title: data[n].title,
        desc: data[n].desc
    }
    data.unshift(movie)
    // 重新渲染list部分
    renderList()
}
// 删除movie
function remove(item) {
    data = data.filter(m => m != item)
    // 重新渲染list部分
    renderList()
}
// 排序
function sortList(sortItem) {
    data.sort((a, b) => {
        if (a[sortItem] > b[sortItem]) {
            return 1
        }
        if (a[sortItem] < b[sortItem]) {
            return -1
        }
        return 0
    })
    // 重新渲染list部分
    renderList()
}

// 列表渲染
function renderList() {
    let listView = getListView()
    oldListView = patch(oldListView, listView)
}
// 获取列表虚拟dom
function getListView() {
    let listView = h("div#list", {
        hook: {
            insert: (vnode) => { console.log('insert') }
        }
    }, data.map(item => h(
        'div.listItem', { style: { display: 'flex' } }, [
        h('div', { style: { marginRight: '10px' } }, item.rank),
        h('div', { style: { marginRight: '10px' } }, item.title),
        h('div', item.desc),
        h('div', { on: { click: () => remove(item) } }, 'x')
    ]
    )))
    if (oldListView == undefined) {
        oldListView = listView
    }
    return listView
}

// 画整个页面及列表
function render() {
    // 画原始数据列表
    let listView = getListView()
    // 画页面部分+列表
    let view = h("div#container.cls", [
        h('h1', 'Top 10 movies'),
        h('div.flex_j_b.b_margin10', [
            h('div', [
                h('span.r_margin10', 'Sort by:'),
                ...sortItems.map(item => h('span.r_margin10', {
                    on: { click: () => sortList(item) }
                }, item))
            ]),
            h('div.btn', {
                on: { click: add }
            }, 'Add')
        ]),
        listView
    ])
    return view
}

// 刚加载的时候，画整个页面
window.addEventListener('DOMContentLoaded', () => {
    var app = document.getElementById('app')
    var view = render()
    patch(app, view)
})
